<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="业务工单号" prop="orderNumber" label-width="200">
        <el-input
          v-model="queryParams.orderNumber"
          placeholder="请输入业务工单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="故障等级" prop="faultLevel">
        <el-select v-model="queryParams.faultLevel" placeholder="请选择故障等级" clearable>
          <el-option
            v-for="dict in dict.type.gelly_fault_level"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="报告人" prop="userId">
        <el-select v-model="queryParams.reporterId" placeholder="请选择报告人" clearable>
          <el-option
            v-for="user in users"
            :key="user.userId"
            :label="user.userName"
            :value="user.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="异常类型" prop="abnormalType">
        <el-select v-model="queryParams.abnormalType" placeholder="请选择异常类型" clearable>
          <el-option
            v-for="dict in dict.type.gelly_abnormal_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="工单状态" prop="orderStatus">
        <el-select v-model="queryParams.orderStatus" placeholder="请选择工单状态" clearable>
          <el-option
            v-for="dict in dict.type.gelly_order_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="故障发生时间" label-width="300">
        <el-date-picker
          v-model="daterangeOccurrenceTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['fault:order:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['fault:order:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['fault:order:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['fault:order:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection"  align="center" />
      <el-table-column label="ID" align="center" prop="id" width="45"/>
      <el-table-column label="业务工单号" align="center" prop="orderNumber" />

      <el-table-column label="报告人" align="center" prop="reporterId">
        <template slot-scope="scope">
          {{ getUserLabel(scope.row.reporterId) }}
        </template>
      </el-table-column>


      <el-table-column label="异常类型" align="center" prop="abnormalType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.gelly_abnormal_type" :value="scope.row.abnormalType"/>
        </template>
      </el-table-column>

      <el-table-column label="受影响的轴向" align="center" prop="affectedAxes" />
      <el-table-column label="故障等级" align="center" prop="faultLevel">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.gelly_fault_level" :value="scope.row.faultLevel"/>
        </template>
      </el-table-column>
      <el-table-column label="故障发生时间" align="center" prop="occurrenceTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.occurrenceTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="工单状态" align="center" prop="orderStatus">
        <template slot-scope="scope">
          <el-tag :class="getOrderStatusClass(scope.row.orderStatus)">
            <i v-if="scope.row.orderStatus === 0" class="el-icon-warning" style="margin-right: 5px;"></i>
            <i v-else-if="scope.row.orderStatus === 1" class="el-icon-refresh" style="margin-right: 5px;"></i>
            <i v-else-if="scope.row.orderStatus === 2" class="el-icon-check" style="margin-right: 5px;"></i>
            {{ getOrderStatusLabel(scope.row.orderStatus) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            :icon="getActionIcon(scope.row.orderStatus)"
            @click="handleOrderAction(scope.row)"
            v-hasPermi="['fault:order:edit', 'fault:order:view']"
          >
            {{ getActionText(scope.row.orderStatus) }}
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['fault:order:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改工单列表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="故障等级" prop="faultLevel">
          <el-select v-model="form.faultLevel" placeholder="请选择故障等级">
            <el-option
              v-for="dict in dict.type.gelly_fault_level"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="故障发生时间" prop="occurrenceTime">
          <el-date-picker clearable
            v-model="form.occurrenceTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择故障发生时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="异常类型" prop="abnormalType">
          <el-select v-model="form.abnormalType" placeholder="请选择异常类型">
            <el-option
              v-for="dict in dict.type.gelly_abnormal_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOrder, getOrder, delOrder, addOrder, updateOrder,exportOrder } from "@/api/fault/order";
import { listUser } from "@/api/system/user";
export default {
  name: "Order",
  dicts: ['gelly_order_status', 'gelly_abnormal_type', 'gelly_fault_level'],
  data() {
    return {
      // 用户数据
      users:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 工单列表表格数据
      orderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      daterangeOccurrenceTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderNumber: null,
        faultLevel: null,
        reporterId: null,
        occurrenceTime: null,
        abnormalType: null,
        orderStatus: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        faultLevel: [
          { required: true, message: "故障等级不能为空", trigger: "change" }
        ],
        reporterId: [
          { required: true, message: "报告人不能为空", trigger: "change" }
        ],
        occurrenceTime: [
          { required: true, message: "故障发生时间不能为空", trigger: "blur" }
        ],
        abnormalType: [
          { required: true, message: "异常类型不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getUsers();
  },
  methods: {
    handleOrderAction(row) {
      if (row.orderStatus === 2) {
        // 已完成 - 查看工单详情
        this.handleView(row);
      } else if (row.orderStatus === 1) {
        // 处理中 - 跳转到工单持续处理页面
        this.handleContinueProcessing(row);
      } else {
        // 待处理 - 跳转到工单创建/编辑页面
        this.handleStartProcessing(row);
      }
    },
    handleView(row) {
      // 跳转到工单详情页面
      console.log('跳转到详情页，工单数据:', row);
      console.log('工单ID:', row.id);
      console.log('跳转路径:', `/real/workorder/detail/${row.id}`);

      this.$router.push({
        path: `/real/workorder/detail/${row.id}`
      }).catch(error => {
        console.error('路由跳转失败:', error);
        this.$message.error('页面跳转失败: ' + error.message);
      });
    },

    // 处理待处理状态的工单 - 跳转到工单持续处理页面（第一次处理）
    handleStartProcessing(row) {
      const workOrderId = row.orderNumber || row.id;
      // 跳转到工单持续处理页面进行第一次处理
      this.$router.push({
        path: `/real/workorder/continue/${workOrderId}`,
        query: {
          id: row.id,
          orderNumber: row.orderNumber,
          firstTime: true // 标识为第一次处理
        }
      });
    },

    // 处理处理中状态的工单 - 跳转到工单持续处理页面
    handleContinueProcessing(row) {
      const workOrderId = row.orderNumber || row.id;
      // 跳转到工单持续处理页面
      this.$router.push({
        path: `/real/workorder/continue/${workOrderId}`,
        query: {
          id: row.id,
          orderNumber: row.orderNumber
        }
      });
    },
    getOrderStatusLabel(status) {
      const statusMap = {
        0: '待处理',
        1: '处理中',
        2: '已完成'
      };
      return statusMap[status] || '未知';
    },

    // 获取操作按钮的图标
    getActionIcon(status) {
      switch (status) {
        case 0: return 'el-icon-edit'; // 待处理 - 编辑图标
        case 1: return 'el-icon-refresh'; // 处理中 - 继续图标
        case 2: return 'el-icon-view'; // 已完成 - 查看图标
        default: return 'el-icon-edit';
      }
    },

    // 获取操作按钮的文本
    getActionText(status) {
      switch (status) {
        case 0: return '开始处理'; // 待处理
        case 1: return '继续处理'; // 处理中
        case 2: return '查看详情'; // 已完成
        default: return '处理';
      }
    },
    getOrderStatusClass(status) {
      switch (status) {
        case 0:
          return 'status-tag status-pending'; // 待处理 - 灰色
        case 1:
          return 'status-tag status-processing'; // 处理中 - 蓝色
        case 2:
          return 'status-tag status-completed'; // 已完成 - 绿色
        default:
          return 'status-tag';
      }
    },
    getUserLabel(userId) {
      const user = this.users.find(u => u.userId === userId);
      return user ? user.userName : '未知';
    },
    getUsers() {
      listUser().then(response => {

        this.users = response.rows;
        console.log(this.users)
      });
    },
    /** 查询工单列表列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeOccurrenceTime && '' != this.daterangeOccurrenceTime) {
        this.queryParams.params["beginOccurrenceTime"] = this.daterangeOccurrenceTime[0];
        this.queryParams.params["endOccurrenceTime"] = this.daterangeOccurrenceTime[1];
      }
      listOrder(this.queryParams).then(response => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        orderNumber: null,
        faultLevel: null,
        reporterId: null,
        occurrenceTime: null,
        abnormalType: null,
        affectedAxes: [],
        orderStatus: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeOccurrenceTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      // 跳转到工单创建页面
      this.$router.push({
        path: '/real/workorder',
        query: {
          mode: 'create' // 标识为创建模式
        }
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getOrder(id).then(response => {
        this.form = response.data;
        this.form.affectedAxes = this.form.affectedAxes.split(",");
        this.open = true;
        this.title = "修改工单列表";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.affectedAxes = this.form.affectedAxes.join(",");
          if (this.form.id != null) {
            updateOrder(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrder(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除工单列表编号为"' + ids + '"的数据项？').then(function() {
        return delOrder(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** md文件导出按钮操作 */
    async handleExport() {
      try {
        this.$modal.loading("正在导出数据，请稍候...");
        const response = await exportOrder(); // response 是 Blob
        console.log("response",response)
        // 直接用 response 创建 Blob
        const blob = new Blob([response], { type: 'text/markdown;charset=utf-8' });

        // 创建下载链接
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;

        // 生成文件名
        const now = new Date();
        const timestamp = now.getFullYear() +
          String(now.getMonth() + 1).padStart(2, '0') +
          String(now.getDate()).padStart(2, '0') + '_' +
          String(now.getHours()).padStart(2, '0') +
          String(now.getMinutes()).padStart(2, '0') +
          String(now.getSeconds()).padStart(2, '0');
        link.download = `工单列表_${timestamp}.md`;

        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);

        this.$modal.msgSuccess("导出成功");
      } catch (error) {
        console.error('导出失败:', error);
        this.$modal.msgError("导出失败: " + (error.message || "未知错误"));
      } finally {
        this.$modal.closeLoading();
      }
    }
  }
};

</script>
<style scoped>
.status-tag {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  min-width: 76px;
  height: 26px;
  padding: 0 12px;
  font-size: 12px;
  font-weight: 600; /* 加粗文字提高鲜艳背景下的可读性 */
  line-height: 1;
  border-radius: 12px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.2s ease;
  text-shadow: 0 1px 1px rgba(0, 0, 0, 0.2); /* 鲜艳色背景需文字阴影增强层次 */
}

/* 待处理 - 醒目黄色 */
.status-pending {
  background-color: #FFD600;
  color: #754C00;
  border: 1px solid #E6B800;
}

/* 处理中 - 活力蓝色 */
.status-processing {
  background-color: #2196F3;
  color: #FFFFFF;
  border: 1px solid #0D8BF2;
}

/* 已完成 - 成功绿色 */
.status-completed {
  background-color: #4CAF50;
  color: #FFFFFF;
  border: 1px solid #3D8C40;
}

/* 悬停效果 - 增强交互反馈 */
.status-tag:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
  filter: brightness(1.05); /* 轻微提亮 */
}
</style>

